<template>
  <div class="mod-user">
    <el-form
      :inline="true"
      :data="dataForm"
      @keyup.enter.native="getUserList()"
    >
      <el-form-item prop="mobile">
        <el-input
          v-model="dataForm.mobile"
          placeholder="电话号码"
          clearable
        ></el-input>
      </el-form-item>
      <el-form-item prop="name">
        <el-input
          clearable
          v-model="dataForm.name"
          placeholder="姓名"
        ></el-input>
      </el-form-item>
      <el-form-item prop="type">
        <el-select clearable v-model="dataForm.type" placeholder="用户类型">
          <el-option
            v-for="item in typeList"
            :key="item.id"
            :value="item.id"
            :label="item.name"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="departmentId">
        <department-select-tree clearable v-model="dataForm.departmentId" />
      </el-form-item>
      <el-form-item prop="status">
        <el-select v-model="dataForm.status" clearable placeholder="用户状态">
          <el-option label="正常" :value="1" />
          <el-option label="禁用" :value="0" />
        </el-select>
      </el-form-item>
      <el-form-item prop="date">
        <el-date-picker
          type="daterange"
          v-model="dataForm.date"
          clearable
          placeholder="日期"
          value-format="yyyy-MM-DD"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item prop="miniUse">
        <el-select
          clearable
          v-model="dataForm.miniUse"
          placeholder="小程序使用状态"
        >
          <el-option label="已使用" :value="1"></el-option>
          <el-option label="未使用" :value="0"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="miniAttention">
        <el-select
          clearable
          v-model="dataForm.miniAttention"
          placeholder="小程序关注状态"
        >
          <el-option label="已关注" :value="1"></el-option>
          <el-option label="未关注" :value="0"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="getUserList">查询</el-button>
        <el-button
          @click="addOrUpdateHandle()"
          v-if="isAuth('feature:user:add')"
          type="primary"
          >新增</el-button
        >
        <el-button
          v-if="isAuth('feature:user:delete')"
          type="danger"
          :disabled="dataListSelections.length <= 0"
          @click="deleteHandle()"
          >批量删除</el-button
        >
        <el-button type="info" @click="resrt()">重置</el-button>
        <el-button type="info" @click="refresh">刷新</el-button>
      </el-form-item>
      <el-form-item>
        <!-- 表格的导入导出 -->
        <el-button @click="showExcelDialog = true">excel导入</el-button>
        <el-button @click="exportEmployee">excel导出</el-button>
      </el-form-item>
    </el-form>
    <el-table
      :data="dataList"
      v-loading="dataListLoading"
      @selection-change="selectionChangeHandle"
      style="width: 100%"
    >
      <el-table-column
        type="selection"
        header-align="center"
        align="center"
        width="50"
      >
      </el-table-column>
      <el-table-column
        fixed="left"
        prop="personalNumber"
        width="150"
        label="学号/工号"
      >
      </el-table-column>
      <el-table-column fixed="left" prop="username" width="150" label="用户名">
      </el-table-column>
      <el-table-column prop="name" width="100" label="真实姓名">
      </el-table-column>
      <el-table-column prop="mobile" width="150" label="电话号码">
      </el-table-column>
      <el-table-column
        prop="type"
        header-align="center"
        align="center"
        width="100"
        label="用户类型"
      >
        <template slot-scope="scope">
          {{
            typeList.find((item) => item.id === scope.row.type)
              ? typeList.find((item) => item.id === scope.row.type).name
              : ''
          }}
        </template>
      </el-table-column>
      <el-table-column prop="email" width="200" label="邮箱"> </el-table-column>
      <el-table-column prop="departmentName" width="100" label="所属部门">
      </el-table-column>
      <el-table-column
        prop="status"
        header-align="center"
        align="center"
        width="100"
        label="状态"
      >
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status === 0" size="small" type="danger"
            >禁用</el-tag
          >
          <el-tag v-else size="small">正常</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="memo" width="200" label="备注">
        <template slot-scope="scope">
          <div class="cell-ellipsis">{{ scope.row.memo }}</div>
        </template>
      </el-table-column>
      <el-table-column
        prop="miniUse"
        width="150"
        align="center"
        label="小程序使用状态"
      >
        <template slot-scope="scope">
          <el-tag v-if="scope.row.miniUse === 0" size="small" type="danger"
            >未使用</el-tag
          >
          <el-tag v-else size="small">已使用</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="miniAttention"
        width="150"
        align="center"
        label="小程序关注状态"
      >
        <template slot-scope="scope">
          <el-tag
            v-if="scope.row.miniAttention === 0"
            size="small"
            type="danger"
            >未关注</el-tag
          >
          <el-tag v-else size="small">已关注</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" width="150" label="创建时间">
      </el-table-column>
      <el-table-column fixed="right" width="150" label="操作">
        <template slot-scope="scope">
          <el-button
            type="text"
            size="small"
            @click="resetPassword(scope.row.userId)"
          >重置密码</el-button
          >
          <el-button
            type="text"
            size="small"
            @click="addOrUpdateHandle(scope.row.userId)"
            >修改</el-button
          >
          <el-button
            type="text"
            size="small"
            @click="deleteHandle(scope.row.userId)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :current-page="pageIndex"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper"
    >
    </el-pagination>
    <!-- 控制Excel弹层 -->
    <user-import-excel
      :show-excel-dialog.sync="showExcelDialog"
      :uploadSuccess="uploadExcelFinish"
    ></user-import-excel>
    <!-- 放置添加/修改用户弹层 -->
    <user-add-or-update
      v-if="addOrUpdateVisible"
      ref="addOrUpdate"
      @refreshDataList="getUserList"
    />
  </div>
</template>

<script>
import DepartmentSelectTree from './department-select-tree.vue'
import UserAddOrUpdate from './user-add-or-update.vue'
import UserImportExcel from './user-import-excel.vue'
import RepairAddOrUpdate from './repair-add-or-update.vue'
export default {
  components: {
    RepairAddOrUpdate,
    UserImportExcel,
    DepartmentSelectTree,
    UserAddOrUpdate
  },
  data() {
    return {
      dataListSelections: [],
      typeList: [
        {
          id: 0,
          name: '管理员'
        },
        {
          id: 2,
          name: '职工'
        },
        {
          id: 3,
          name: '医护'
        },
        {
          id: 4,
          name: '学生'
        },
        {
          id: 5,
          name: '维修人员'
        },
        {
          id: 1,
          name: '教师'
        }
      ],
      dataList: [
        {
          username: 202113840528,
          name: 'John',
          mobile: '17777777777',
          type: 2,
          email: 'john@example.com',
          departmentName: '技术部',
          status: 1,
          memo: '这是一条测试数据啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊',
          miniUse: 0,
          miniAttention: 0,
          createTime: '2024-02-19 11:11:11'
        }
      ],
      dataForm: {
        username: null,
        name: null,
        type: null,
        departmentId: null,
        status: null,
        miniUse: null,
        miniAttention: null,
        mobile: null
      },
      dataListLoading: false,
      showExcelDialog: false, // 打开Excel对话框
      addOrUpdateVisible: false,
      // 分页
      pageIndex: 1,
      pageSize: 10,
      totalPage: 0
    }
  },
  created() {
    this.getUserList()
  },

  methods: {
    uploadExcelFinish() {
      this.getUserList()
    },
    resrt() {
      this.dataForm = {}
      this.dataForm.departmentId = null
      this.getUserList()
    },
    exportEmployee() {
      console.log('下载Excel')
      this.$http({
        url: this.$http.adornUrl('sys/user/exportUser'),
        method: 'post',
        data: this.dataForm,
        responseType: 'blob'
      }).then(({ data }) => {
        const link = document.createElement('a')
        let blob = new Blob([data], { type: 'application/vnd.ms-excel' })
        link.style.display = 'none'
        link.href = URL.createObjectURL(blob)
        link.setAttribute('download', '导出用户信息表')
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
      })
    },
    // 每页数
    sizeChangeHandle(val) {
      this.pageSize = val
      this.pageIndex = 1
      this.getUserList()
    },
    // 当前页
    currentChangeHandle(val) {
      this.pageIndex = val
      this.getUserList()
    },
    // 多选
    selectionChangeHandle (val) {
      this.dataListSelections = val
    },
    // 新增 / 修改
    addOrUpdateHandle(id) {
      this.addOrUpdateVisible = true
      this.$nextTick(() => {
        this.$refs.addOrUpdate.init(id)
      })
    },
    // 修改密码
    resetPassword(id) {
      // this.addOrUpdateVisible = true
      // this.$nextTick(() => {
      //   this.$refs.addOrUpdate.init(id)
      // })
      this.$http({
        url: this.$http.adornUrl('/sys/u/resetPassword?userId='+id),
        method: 'put',
        data: this.$http.adornData({
          // ...this.dataForm,
          page: this.pageIndex,
          size: this.pageSize
        })
      }).then((res) => {
        if (res.data.code === 0) {
          this.$notify({
            title: '成功',
            message: res.data.msg,
            type: 'success',
            duration: 3000
          })
        } else if (res.data.code === 500) {
          this.$notify({
            title: '错误',
            message: res.data.msg,
            type: 'error',
            duration: 3000
          })
        }
        // this.dataList = res.data.data
        // this.totalPage = res.data.total
      })
    },
    // 获取数据
    getUserList() {
      this.dataForm = {
        ...this.dataForm,
        startTime: this.dataForm.date ? this.dataForm.date[0] : '',
        endTime: this.dataForm.date ? this.dataForm.date[1] : ''
      }
      console.log(this.dataForm)

      this.$http({
        url: this.$http.adornUrl('sys/visitor/getVisitorList'),
        method: 'post',
        data: this.$http.adornData({
          ...this.dataForm,
          page: this.pageIndex,
          size: this.pageSize
        })
      }).then((res) => {
        console.log(res.data)
        this.dataList = res.data.data
        this.totalPage = res.data.total
      })
    },
    // 刷新
    refresh() {
      //this.dataForm = {}
      this.getUserList()
    },
    // 删除
    deleteHandle(id) {
      var ids = id
        ? [id]
        : this.dataListSelections.map((item) => {
            return item.userId
          })
      this.$confirm(
        `确定对[id=${ids.join(',')}]进行[${id ? '删除' : '批量删除'}]操作?`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(() => {
          console.log(ids)
          this.$http({
            url: this.$http.adornUrl('sys/visitor/deleteVisitorByIds'),
            method: 'put',
            params: { ids },
            // 主要是以下四行代码 , 传数组参数
            paramsSerializer: function (params) {
              const ids = params.ids.map((_) => `ids=${_}`).join('&')
              return `${ids}`
            }
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.getUserList()
                }
              })
            } else {
              this.$message.error(data.msg)
            }
          })
        })
        .catch(() => {})
    }
  }
}
</script>

<style lang="scss" scoped>
.opeate-tools {
  margin: 10px;
}
.cell-ellipsis {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>
